package com.engineering.elink.service.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.engineering.elink.common.ErrorType;
import com.engineering.elink.domain.Course;
import com.engineering.elink.domain.Enroll;
import com.engineering.elink.service.EnrollService;
import com.engineering.elink.util.ResJsonUtil;
import com.engineering.elink.videodao.CourseMapper;
import com.engineering.elink.videodao.EnrollMapper;

/**
 * 报名业务实现类
 */
@Service
public class EnrollServiceImpl implements EnrollService{

	@Autowired
	private CourseMapper courseMapper;
	
	@Autowired
	private EnrollMapper enrollMapper;
	
//	@Autowired
//	private PersonDynamicHessianService personDynamicHessianService;
	
	/**
	 * 
	 * 简单描述该方法的实现功能（可选）. 
	 * @see com.engineering.elink.service.EnrollService#getCourseEnroll(java.lang.Integer)
	 */
	@Override
	public Map<String, Object> getCourseEnroll(Integer courseId) {
		
		Course course=courseMapper.selectByPrimaryKey(courseId);
		if(course==null)
			return ResJsonUtil.getMap(ErrorType.COURSE_ERROR);
		
		return ResJsonUtil.getMap(ErrorType.SUCCESS, course);
	}

	/**
	 * 
	 * 简单描述该方法的实现功能（可选）. 
	 * @see com.engineering.elink.service.EnrollService#add(java.lang.Integer, java.lang.String)
	 */
	@Override
	public Map<String, Object> add(Integer courseId, String userId) {
		Course course=courseMapper.selectByPrimaryKey(courseId);
		if(course==null)
			return ResJsonUtil.getMap(ErrorType.COURSE_ERROR);
		
		int count=enrollMapper.selectCountEnroll(courseId, userId);
		if(count>0){
			return ResJsonUtil.getMap(ErrorType.ENROLL_ERROR);
		}
		
		//添加报名记录
		enrollMapper.insertSelective(new Enroll(courseId,userId));
		
		//更新课程学习人数
		course.setDownloadCount(course.getDownloadCount()+1);
		courseMapper.updateByPrimaryKeySelective(course);
		
//		try{
//			personDynamicHessianService.addPersonDynamic(5, 0, course.getTitle(), course.getIntroduction(), userId, String.valueOf(course.getCourseId()));
//		}catch(Exception e){
//			e.printStackTrace();
//		}
		
		return ResJsonUtil.getMap(ErrorType.SUCCESS);
	}

	@Override
	public Map<String, Object> cancelCourseEnroll(Integer courseId, String userId) {
		enrollMapper.deleteByCourseEnroll(courseId, userId);
//		try{
//			personDynamicHessianService.removePersonDynamic(5, String.valueOf(courseId));
//		}catch(Exception e){
//			e.printStackTrace();
//		}
		return ResJsonUtil.getMap(ErrorType.SUCCESS);
	}
	
}
